package com.merryituxz.o2o.util;


import javax.crypto.*;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 对称加密算法DES
 */
public class DESUtil {
    private static Key key;

    private static String KEY_STR = "myKey";
    private static String CHARSET_NAME = "UTF-8";
    private static String ALGORITHM = "DES";
    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final Base64.Decoder decoder = Base64.getDecoder();

    static {
        try {
            // 生成DES算法对象
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            // SHA1安全策略
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // 设置密钥种子
            secureRandom.setSeed(KEY_STR.getBytes());
            // 初始化基于SHA1的算法对象
            generator.init(secureRandom);
            // 生成密钥对象
            key = generator.generateKey();
            generator = null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 基于BASE64编码加密字符串
     *
     * @return 加密后的字符串
     */
    public static String getEncryptString(String str) {
        // 基于BASE64编码
        try {
            byte[] bytes = str.getBytes(CHARSET_NAME);
            // 获取加密对象, 初始化密码信息并进行加密
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return encoder.encodeToString(doFinal);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解码基于BASE64编码加密后的字符串
     *
     * @param str 待解码字符串
     * @return 解码后的字符串
     */
    public static String getDecryptString(String str) {
        try {
            byte[] bytes = decoder.decode(str);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSET_NAME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public static void main(String[] args) {
//        System.out.println(getEncryptString("log"));
//        System.out.println(getEncryptString("log965019948"));
//        System.out.println(getDecryptString("StAfo3OjLoQ="));
//        System.out.println(getDecryptString("W7xzhTejvl2xDHmunr2ctw=="));
//    }
}
